package com.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shiro.pojo.UserBean;
import com.shiro.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	
	/**
	 * 
	* @Title: index 
	* @Description: TODO(登录成功，跳转到首页) 
	* @param model
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping("/index")
	public String index(Model model){
		/*List<UserBean> list = userService.findUserAll();
		model.addAttribute("user",list.get(0));*/
		Session session = SecurityUtils.getSubject().getSession();
		UserBean user = (UserBean)session.getAttribute("user");
		System.out.println(user);
		return "Page/index";
	}
    @RequiresRoles("admin")
	@RequestMapping("/list")
	public String list(){
		return "Page/list";
	}
	/**
	 * 
	* @Title: login 
	* @Description: TODO(登录方法) 
	* @param username
	* @param password
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping("/login")
	public String login(String username,String password){
		logger.info("进入登录方法");
		logger.info("获取shiro的token和安全管理器");
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			/*System.out.println("--------------进入shiro的授权方法--------------");
			System.out.println(subject.hasRole("admin"));*/
		} catch (AuthenticationException e) {
			e.printStackTrace();
			return "relogin";
		}
		return "redirect:/user/index";
	}
	/**
	 * 
	* @Title: relogin 
	* @Description: TODO(返回登录页面) 
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping("/relogin")
	public String relogin(){
		return "login";
	}
	/**
	 * 
	* @Title: authority 
	* @Description: TODO(提示无权限) 
	* @return String    返回类型
	* @throws
	 */
	@RequestMapping("/noAuthority")
	public String authority(){
		return "noauthority";
	}
}
